package chatmsgservicelogic

import (
	"context"

	"paper-pro/app/chat/rpc/internal/svc"
	"paper-pro/app/chat/rpc/pb"

	"github.com/pkg/errors"
	"github.com/zeromicro/go-zero/core/logx"
)

type ListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ListLogic {
	return &ListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *ListLogic) List(in *pb.ChatMsgListReq) (*pb.ChatMsgListResp, error) {
	msgs, err := l.svcCtx.ChatMsgModel.FindMany(l.ctx, in.DialogId, in.UserId, in.Limit)
	if err != nil {
		return nil, errors.Wrapf(err, "Chat Msgs List: failed, by Dialog Id: %s, User Id: %d", in.DialogId, in.UserId)
	}
	respMsgs := make([]*pb.ChatMsg, 0, len(msgs))
	for _, msg := range msgs {
		respMsgs = append(respMsgs, &pb.ChatMsg{
			Id:       msg.ID.Hex(),
			UpdateAt: msg.UpdateAt.Unix(),
			CreateAt: msg.CreateAt.Unix(),
			Content:  msg.Content,
			Role:     msg.Role,
			ChatAt:   msg.ChatAt.Unix(),
			DialogID: msg.DialogID.Hex(),
			UserId:   msg.UserId,
		})
	}

	return &pb.ChatMsgListResp{
		Msgs: respMsgs,
	}, nil
}
